<template>
  <!-- <div class='container'>添加目录对话框</div> -->
 <el-dialog :title="`${data.id?'修改':'新增'}目录`" :visible.sync="show" width="20%" >
    <!-- 表单 -->
    <el-form label-width="80px" ref="formRef" :model="form" :rules="rules">
      <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id">
       <el-select style="width:100%" v-model="form.subjectID">
            <el-option
            v-for="item in subjectOptions"
            :value = "item.value"
            :label = "item.label"
            :key="item.value"
            ></el-option>
          </el-select>
      </el-form-item>
       <el-form-item label="目录名称" prop="directoryName">
        <el-input   placeholder="请输入目录名称" v-model="form.directoryName"/>
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-button  @click="show=false">取消</el-button>
      <el-button type="primary" @click="submit()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys'
import { simple as subjectList } from '@/api/hmmm/subjects'
export default {
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      show: false,
      // 表单数据
      form: {
        id: null,
        subjectID: null,
        directoryName: null
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, type: 'number', message: '请选择所属学科', tirgger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', tirgger: 'blur' }
        ]
      },
      subjectOptions: []
    }
  },
  async created () {
    // 学科下拉选项
    const { data: subjectArr } = await subjectList()
    this.subjectOptions = subjectArr
  },
  methods: {
    open () {
      this.show = true
      if (this.data.id) {
        const { id, subjectID, directoryName } = this.data
        this.form = { id, subjectID, directoryName }
      } else {
        this.form = {
          id: null,
          subjectID: +this.$route.query.id || null,
          directoryName: null
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    async submit () {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          // 提交
          if (!this.data.id) {
            // 新增
            await add(this.form)
          } else {
            // 修改
            this.form.id = this.data.id
            await update(this.form)
          }
          this.$message.success('操作成功')
          this.show = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
